<?php

namespace App\GameChannel\Sdks;

use App\GameChannel\LoginNotify;
use App\GameChannel\SdkBase;
use App\Models\Orders;
use App\Models\UserAccountBindChannel;
use App\Services\PayService;
use App\Services\UserHutongService;
use Illuminate\Http\Request;

// 我方H5sdk
// 只需要处理登录和创单逻辑即可，支付成功回调将由 switch_pay 逻辑进行处理和最终发货
class H5Sdk extends SdkBase
{
    public function login(Request $request): LoginNotify
    {
        $notify = $this->loginNotify;

        // 公众号用户openid
        $openid = $request->input('openid') ?? '';
        // 小程序用户openid
        $wx_openid = $request->input('wx_openid') ?? '';

        // h5用户openid
        $h5_openid = $request->input('h5_openid') ?? '';
        // 如果不为空，则表示用户是基于H5官方账号登录的
        if (!empty($h5_openid)) {
            $bind = UserHutongService::getInstance()->getBindByAccount($this->channel, $h5_openid);
            if ($bind) {
                $openid = $bind->channel_openid;
            } else {
                $openid = $h5_openid;
            }
        }

        $notify->openid = $openid;
        $notify->openid2 = $wx_openid;

        return $notify;
    }

    public function payInit(Orders $order, Request $request)
    {
        $open_pay_list = PayService::getInstance()->getOpenPayList($order->game_id, $order->game_channel_id);

        $data = [
            'pay_url' => $this->switchPayUrl($order),
            'open_pay_list' => $open_pay_list,
        ];

        return $data;
    }
}
